package cn.itcast.service.cargo.impl;

import cn.itcast.dao.cargo.ContractDao;
import cn.itcast.dao.cargo.ContractProductDao;
import cn.itcast.dao.cargo.ExtCproductDao;
import cn.itcast.domain.cargo.*;
import cn.itcast.service.cargo.ContractService;
import cn.itcast.vo.ContractProductVo;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class ContractServiceImpl implements ContractService {
    @Autowired
    private ContractDao contractDao;
    @Autowired
    private ContractProductDao contractProductDao;
    @Autowired
    private ExtCproductDao extCproductDao;

    @Override
    public Contract findById(String id) {
        return contractDao.selectByPrimaryKey(id);
    }

    @Override
    public void save(Contract contract) {
        contractDao.insertSelective(contract);
    }

    @Override
    public void update(Contract contract) {
        contractDao.updateByPrimaryKeySelective(contract);
    }

    @Override
    public void delete(String id) {
        Contract contract = contractDao.selectByPrimaryKey(id);
        // 删除合同时，需要同步删除其下的货物及货物下的附件信息
        ContractProductExample productExample = new ContractProductExample();
        productExample.createCriteria().andContractIdEqualTo(id);
        List<ContractProduct> products = contractProductDao.selectByExample(productExample);
        for (ContractProduct product : products) {
            // 同步删除货物下的附件信息
            ExtCproductExample cproductExample = new ExtCproductExample();
            cproductExample.createCriteria().andContractProductIdEqualTo(product.getId());
            List<ExtCproduct> cproducts = extCproductDao.selectByExample(cproductExample);
            for (ExtCproduct cproduct : cproducts) {
                extCproductDao.deleteByPrimaryKey(cproduct.getId());
            }
            // 同步删除合同下货物信息
            contractProductDao.deleteByPrimaryKey(product.getId());
        }
        // 最后删除合同
        contractDao.deleteByPrimaryKey(id);
    }

    @Override
    public PageInfo findAll(ContractExample example, int page, int size) {
        PageHelper.startPage(page, size);
        List<Contract> list = contractDao.selectByExample(example);
        return new PageInfo<Contract>(list, 5);
    }

    @Override
    public List<ContractProductVo> findContractProductVoByShipTime(String inputDate, String companyId) {
        return contractDao.findContractProductVoByShipTime(inputDate, companyId);
    }
}
